import { type Ref, ref, unref, onMounted, onUnmounted, reactive } from "vue"
import { useMessage } from "/@/hooks/web/useMessage"
import { TaskCode, BizType } from "/@/api/sys/model/msgPushModel"
import { sendCaptchaMsg } from "/@/api/sys/msgPush"
import { getImageCaptcha } from "/@/api/auth"
import { useModal } from "/@/components/Modal"

// 倒计时60s
const TIME_COUNT = 60

export interface VerifyProps {
  taskCode: TaskCode
  bizType: String
  api?: Function
  apiParams?: Ref<any>
}

export const useSendCaptchaMsg = (props: VerifyProps) => {
  const timer = ref<any>()
  const count = ref(TIME_COUNT)
  const { createMessage } = useMessage()
  const disabled = ref(false)
  const verifyInfo = reactive<any>({})
  const butName = ref("点击获取")
  let isReset = false
  const [registerManMachineVerifyModal, { openModal: openManMachineVerifyModal }] = useModal()

  verifyInfo.taskCode = props.taskCode
  verifyInfo.bizType = props.bizType
  onMounted(async () => {})

  onUnmounted(() => {
    reset()
  })

  const reset = () => {
    butName.value = "点击获取"
    clearInterval(timer.value)
    timer.value = null
    disabled.value = false
  }

  const startInterval = () => {
    clearInterval(timer.value)
    timer.value = null
    timer.value = setInterval(() => {
      if (count.value > 0 && count.value <= TIME_COUNT) {
        count.value = count.value - 1
        butName.value = count.value + "S"
      } else {
        butName.value = "点击获取"
        count.value = TIME_COUNT
        disabled.value = false
        clearInterval(timer.value)
        timer.value = null
      }
    }, 1000)
  }

  const handleSend = async () => openManMachineVerifyModal(true, {})
  const handleManMachineVerifySuccess = async (data) => {
    verifyInfo.captchaToken = data.token
    verifyInfo.captchaValue = data.captchaValue
    verifyInfo.captchaType = data.captchaType
    isReset = false
    if (!disabled.value) {
      disabled.value = true

      if (props.api) {
        props
          .api({
            toUser: "user",
            bizType: props.bizType,
            taskCode: props.taskCode,
            ...unref(props.apiParams),
            ...verifyInfo,
          })
          .then((res) => {
            startInterval()
            createMessage.success(`验证码已发送, 请注意查收`)
          })
          .catch((res) => {
            reset()
          })
      } else {
        sendCaptchaMsg({
          toUser: "user",
          bizType: props.bizType,
          taskCode: props.taskCode,
          ...unref(props.apiParams),
          ...verifyInfo,
        })
          .then((res) => {
            startInterval()
            createMessage.success(`验证码已发送, 请注意查收`)
          })
          .catch((res) => {
            reset()
          })
      }
    }
  }

  return {
    butName,
    disabled,
    verifyInfo,
    handleSend,
    registerManMachineVerifyModal,
    handleManMachineVerifySuccess,
  }
}
